import { legacy_createStore, applyMiddleware } from "redux"
import thunk from "redux-thunk"
import logger from "redux-logger"
import { ALLSTATE, ALLACTION, SETWORDLIST, GETDETILE, ADDWORD, SHOWCOMMENTTS, ADDCOMMENTTS, LISTITEM } from "../type/store.d"
const initialState = {
    wordList: [],
    detileData: {}
}

const renducer = (state: ALLSTATE = initialState, { type, payload }: ALLACTION) => {
    switch (type) {
        case SETWORDLIST:
            state.wordList = payload
            return { ...state }
        case GETDETILE:
            const list = state.wordList.filter(item => item.id == payload)[0]
            state.detileData = list
            return { ...state }
        case ADDWORD:
            const newList = [...state.wordList]
            newList.unshift(payload)
            state.wordList = newList
            return { ...state }
        case SHOWCOMMENTTS:
            const newComList = [...state.wordList]
            newComList.forEach((item, index) => {
                if (item.id == payload) {
                    item.isComments = !item.isComments;
                }
            })
            state.wordList = newComList
            return { ...state }
        case ADDCOMMENTTS:
            const setnewComList = [...state.wordList]
            setnewComList.forEach((item:LISTITEM, index:number) => {
                if (item.id == payload.id) {
                    item.commentsList && item.commentsList.unshift(payload.value)
                    item.isComments = false
                }
            })
            state.wordList = setnewComList
            return { ...state }
        default:
            return state
    }
}
const store = legacy_createStore(renducer, applyMiddleware(logger, thunk))
export default store